<!-- 
    * 自提点页面
 -->

<template>
    <div class="w750 font-14" :style="{ '--themescolor': themes.color }">
        <div class="d-flex flex-column h-100">
            <div class="bg-fff d-flex p-1">
                <div @click="chooseCity" class="d-flex a-center cursor-pointer" style="flex-basis: auto; flex-grow: 0; flex-shrink: 0">
                    <span class="iconfont iconlocation mr" style="font-size: 14px"></span>
                    <span class="font-12">{{ locationStatus ? locationCity || '定位中...' : '定位失败...' }}</span>
                </div>
                <div class="ml p-1 flex-1 d-flex a-center border rounded-20">
                    <span class="iconfont iconsearch" style="font-size: 14px"></span>
                    <input v-model="params.pointName" class="flex-1 px" style="width: 200px" placeholder="输入搜索门店名称" @keyup.enter="search" />
                    <div @click="search" class="font-12 text-center" style="flex-basis: auto; flex-grow: 0; flex-shrink: 0">搜索</div>
                </div>
            </div>
            <div class="text-999 py">当前位置</div>
            <div class="p-1 d-flex bg-fff border-bottom-10bg">
                <div class="flex-1" v-if="locationStatus">{{ detailAddr || '定位中...' }}</div>
                <div class="flex-1" v-else>定位失败...</div>
                <div class="text-right text-999">
                    <span class="iconfont iconsearch mr" style="font-size: 14px"></span>
                    <span @click="toLocation" class="font-12 text-666 cur cursor-pointer">重新定位</span>
                </div>
            </div>

            <div v-if="ownPoint" class="bg-fff mb-1 px-1">
                <div class="font-14 bg-fff pt-1">分配自提点</div>
                <div class="my-1 pb-15p d-flex" @click="selectPoint(ownPoint)">
                    <div style="width: 80px; height: 80px" class="rounded-5">
                        <img v-if="ownPoint" :src="$imgUrlHead + ownPoint.sinceMentionPicList[0]" alt="" class="w-100 h-100" />
                    </div>
                    <div class="flex-1 ml-1">
                        <p class="line-clamp1 font-16" style="width: auto; max-width: 5rem">{{ ownPoint.pointName }}</p>
                        <p class="text-999 mt font-12" @click.stop="checkLocation(ownPoint)">
                            {{ ownPoint.sinceMentionDetailAddr }}
                            <span class="iconfont iconArrowRight" style="font-size: 14px; color: #c0c4d6"></span>
                        </p>
                        <p class="mt font-12 text-999">营业时间：{{ ownPoint.periodJoin }}</p>
                        <div class="mt text-999 font-12 d-flex j-sb">
                            <div>
                                <span class="pr" v-for="(time, index) in ownPoint.businessHoursList" :key="index">
                                    {{ time.begin }}-{{ time.end }}
                                </span>
                            </div>
                            <a class="mx" :href="'tel:' + ownPoint.contactPhone">
                                <span @click.stop class="iconfont iconphone text-999" style="font-size: 16px"></span>
                            </a>
                        </div>
                    </div>
                </div>
            </div>

            <div v-if="list && list.length">
                <div class="font-14 px-1 bg-fff pt-1">商家自提点</div>
                <van-list
                    v-if="paging.tab"
                    v-model="paging.loading"
                    :finished="paging.finished"
                    :immediate-check="false"
                    finished-text="没有更多了"
                    @load="loadMore"
                >
                    <div class="bg-fff p-1">
                        <div @click="selectPoint(item)" v-for="item in list" :key="item.id" class="my-1 border-bottom pb-15p d-flex">
                            <div style="width: 80px; height: 80px" class="rounded-5">
                                <img
                                    v-if="item.sinceMentionPicList && item.sinceMentionPicList.length"
                                    :src="$imgUrlHead + item.sinceMentionPicList[0]"
                                    alt=""
                                    class="w-100 h-100"
                                />
                                <img v-else src="@/assets/images/default-shop-img.jpg" alt="" class="w-100 h-100" />
                            </div>
                            <div class="flex-1 ml-1">
                                <p class="font-16 d-flex j-sb">
                                    <span class="line-clamp1" style="width: auto; max-width: 5rem">{{ item.pointName }}</span>
                                    <span class="font-12 text-999">{{ item.distance }}km</span>
                                </p>
                                <p class="text-999 mt font-12" @click.stop="checkLocation(item)">
                                    {{ item.sinceMentionDetailAddr }}
                                    <span class="iconfont iconArrowRight" style="font-size: 14px; color: #c0c4d6"></span>
                                </p>
                                <p class="mt font-12 text-999">营业时间：{{ item.periodJoin }}</p>
                                <div class="mt text-999 font-12 d-flex j-sb">
                                    <div>
                                        <span class="pr" v-for="(time, index) in item.businessHoursList" :key="index">
                                            {{ time.begin }}-{{ time.end }}
                                        </span>
                                    </div>
                                    <a class="mx" :href="'tel:' + item.contactPhone">
                                        <span @click.stop class="iconfont iconphone text-999" style="font-size: 16px"></span>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </van-list>
            </div>

            <!-- 局部加载组件 -->
            <part-loading v-model="partLoading" backgroundColor="#fff" height="400px" size="24px" :color="themes.color" />

            <Noempty :pic="require('@/assets/images/review.png')" :title="'附近暂无商家自提点'" v-if="paging.emptylist && !paging.error" />
        </div>

        <van-popup v-model="showCity" position="bottom">
            <van-picker
                title="请选择省份"
                show-toolbar
                :columns="columns"
                :default-index="provinceIndex"
                value-key="value"
                @confirm="onConfirm"
                @cancel="showCity = false"
            />
        </van-popup>
    </div>
</template>

<script>
import { mapState } from 'vuex'
import { geolocationFunc, geocoderFunc } from '@/utils/mapUtils'
import Noempty from 'components/Noempty/Noempty'
import PageUtil from '@/utils/PageUtil'
import { sinceMentionList, assignedSinceMentionPoint } from '@/api/order'
import { loadProvincesByMode } from 'api/common/common.js'
import PartLoading from '@/components/PartLoading/PartLoading'

const pageUtil = new PageUtil(sinceMentionList)

export default {
    components: { Noempty, PartLoading },
    data() {
        return {
            name: '', // 搜索地点
            locationCity: '', // 定位城市

            detailAddr: '', // 详细地址
            paging: {
                tab: false,
                loading: false,
                finished: false,
                error: false, // 是否错误
                emptylist: false // 是否显示列表为空时的样式
            },
            list: [],
            params: {
                provinceId: '',
                pointName: '',
                longitude: '', // 纬度
                latitude: '' // 经度
            },
            locationStatus: true, // false: 定位失败/true: 成功
            showCity: false, // 省份弹窗
            columns: [],
            provinceIndex: 0,

            ownPoint: '', // 自己的自提点
            partLoading: true
        }
    },
    computed: {
        ...mapState(['themes', 'curLocation'])
    },
    mounted() {
        this.getLocation()
        this.getOwnPoint()
    },
    methods: {
        // 分享员自己的自提点
        getOwnPoint() {
            assignedSinceMentionPoint()
                .then((res) => {
                    if (!res.success) return void this.$toast(res.msg)

                    this.ownPoint = res.result
                })
                .catch((err) => {
                })
        },

        // 自动定位
        getLocation() {
            //  沙盒拦截，本地测试环境会报错，上线要解开
            try {
                if (sessionStorage.getItem('location') && sessionStorage.getItem('location') != 'undefined') {
                    let location = JSON.parse(sessionStorage.getItem('location'))
                    sessionStorage.removeItem('location')

                    this.$set(this.params, 'longitude', location.location.lng)
                    this.$set(this.params, 'latitude', location.location.lat)
                    this.detailAddr = location.address + location.name
                    const geocoder = geocoderFunc()
                    geocoder.getAddress([location.location.lng, location.location.lat], (status, result) => {
                        if (status === 'complete' && result.info === 'OK') {
                            const reg = /.+?(省|市|区)/g
                            this.locationCity = result.regeocode.formattedAddress.match(reg)[0]
                            this.loadProvince()
                        }
                    })
                } else {
					if(this.$utils.test.isEmpty(this.curLocation)) { //是否已经加载过 加载过后 curLocation 不为空 解决高德的geolocation.getCurrentPosition加载缓慢
						const geolocation = geolocationFunc()
						geolocation.getCurrentPosition(this.locationComplete)
					} else {
						let result = this.curLocation
						this.$set(this.params, 'longitude', result.position.lng)
						this.$set(this.params, 'latitude', result.position.lat)
						// this.$store.commit('setCurLocation', result)
						this.detailAddr = result.formattedAddress
						this.locationCity = result.addressComponent.province
						this.loadProvince()
					}
                }
            } catch (e) {
                this.$toast.fail('定位失败')
            }
        },

        // 选择省份
        chooseCity() {
            this.showCity = true
        },

        search() {
            pageUtil.loadListByPage(this, this.params)
        },

        // 加载更多
        loadMore() {
            pageUtil.loadListByPageMore()
        },

        // 自动定位成功回调函数
        locationComplete(status, result) {
            if (status !== 'complete') {
                this.$toast.fail('定位失败')
                this.locationStatus = false
                return
            }
			
            this.$set(this.params, 'longitude', result.position.lng)
            this.$set(this.params, 'latitude', result.position.lat)
			this.$store.commit('setCurLocation', result)
            this.detailAddr = result.formattedAddress
            this.locationCity = result.addressComponent.province
            this.locationStatus = true
            this.loadProvince()
        },

        // 重新定位
        toLocation() {
			// this.params.longitude
			// this.params.latitude
            this.$router.push({ name: 'map' })
        },

        // 选择自提点
        selectPoint(item) {
            sessionStorage.setItem('point', JSON.stringify(item))
            this.$router.back()
        },

        // 查看item的地图位置
        checkLocation(item) {
            this.$router.push({ name: 'mapPoint', query: { lng: item.longitude, lat: item.latitude, title: item.pointName } })
        },

        // 选择省份
        onConfirm(value, index) {
            this.provinceIndex = index
            this.locationCity = value.value
            this.$set(this.params, 'provinceId', value.key)
            this.showCity = false
        },

        // 加载所有省份
        loadProvince() {
            loadProvincesByMode({
                mode: 'id'
            })
                .then((res) => {
                    if (!res.success) return this.$toast(res.msg)
                    this.columns = res.result
                    const activeProvinceIndex = res.result.findIndex((item) => this.locationCity.indexOf(item.value) >= 0)
                    this.$set(this.params, 'provinceId', res.result[activeProvinceIndex].key)
                    this.provinceIndex = activeProvinceIndex

                    pageUtil.loadListByPage(this, this.params, {
                        complete: () => {
                            this.partLoading = false
                        }
                    })
                })
                .catch((err) => {
                })
        }
    }
}
</script>
